import * as THREE from 'three'
import { GangTi } from './GangTi.js'
import { huanJing } from '../../huanJing/HuanJing.js'

export class FaGuangTi extends GangTi {
	yanSe = null
	qiangDu = null
	guangJuLi = null
	yinYingJuLi = null
	shiFaGuangTi = true // 是发光体
	dianGuangYuan = new THREE.PointLight() // 点光源
	liang = true // 是否在发光
	/**
	 * 灯光不能太多，报错
	 * 带投影灯光不能太多（16），会报错
	 * @param {Mesh} moXing
	 * @param {Mesh} pengZhuangTi
	 * @param {Number} zhiLiang
	 * @param {Color} yanSe
	 * @param {Number} qiangDu
	 * @param {Number} guangJuLi == 0无限远
	 * @param {Number} yinYingJuLi 投射阴影距离
	 */
	constructor(moXing, pengZhuangTi, zhiLiang, yanSe = 0xffffff, qiangDu = 1, guangJuLi = 100, yinYingJuLi = 100) {
		super(moXing, pengZhuangTi, zhiLiang)

		moXing.castShadow = false
		moXing.receiveShadow = false

		this.yanSe = yanSe
		this.qiangDu = qiangDu
		this.guangJuLi = guangJuLi
		this.yinYingJuLi = yinYingJuLi

		this.faGuang()
	}

	faGuang(liang = true) {
		this.liang = liang

		let yanSe = this.yanSe
		let qiangDu = this.qiangDu
		let guangJuLi = this.guangJuLi
		let yinYingJuLi = this.yinYingJuLi

		this.dianGuangYuan.intensity = qiangDu
		this.dianGuangYuan.color.set(yanSe)
		this.dianGuangYuan.distance = guangJuLi
		let size = 1024
		this.dianGuangYuan.shadow.mapSize.width = size
		this.dianGuangYuan.shadow.mapSize.height = size
		this.dianGuangYuan.shadow.camera.near = 0.04 // 点光源阴影相机为PerspectiveCamera，near不能为0；小于0.04阴影会出问题
		this.dianGuangYuan.shadow.camera.far = yinYingJuLi // 当distance == 0时 far 起作用
		this.dianGuangYuan.shadow.bias = -0.005

		this.moXing.traverse(a => {
			if (a.isMesh && a.material.isMeshStandardMaterial)  {
				a.material.emissive.set(yanSe)
				if (liang) {
					this.moXing.layers.enable(huanJing.houQiChuLi.BLOOM_SCENE)
					this.moXing.add(this.dianGuangYuan)
					a.material.emissiveIntensity = 1
					a.castShadow = false
					a.receiveShadow = false
				}else {
					this.moXing.layers.disable(huanJing.houQiChuLi.BLOOM_SCENE)
					this.moXing.remove(this.dianGuangYuan)
					a.material.emissiveIntensity = 0
					a.castShadow = true
					a.receiveShadow = true
				}
			}
		})
	}

	gengXin(jianGe) {
		super.gengXin(jianGe)
	}
	
	xiaoHui() {
		super.xiaoHui()
		this.dianGuangYuan.dispose()
	}
}